package com.openstack.javasdk;

import com.alibaba.fastjson.JSONObject;
import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient.OSClientV3;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.common.Payload;
import org.openstack4j.model.common.Payloads;
import org.openstack4j.model.identity.v3.Endpoint;
import org.openstack4j.model.identity.v3.Role;
import org.openstack4j.model.identity.v3.Service;
import org.openstack4j.model.identity.v3.User;
import org.openstack4j.model.image.v2.ContainerFormat;
import org.openstack4j.model.image.v2.DiskFormat;
import org.openstack4j.model.image.v2.Image;
import org.openstack4j.openstack.OSFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

@RestController
@RequestMapping(value = "/glance")
public class GlanceModule {

    @GetMapping("/image/list")
    public String imageList() {
        OSClientV3 os = Auth.getOS();
        List<? extends Image> images = os.imagesV2().list();
        return JSONObject.toJSONString(images);
    }

    @GetMapping("/image/query")
    public String imageQuery(@RequestParam(value = "imageId") String imageId) {
        OSClientV3 os = Auth.getOS();
        Image image = os.imagesV2().get(imageId);
        return JSONObject.toJSONString(image);
    }

    @GetMapping("/image/upload")
    public String imageUpload() {
        OSClientV3 os = Auth.getOS();
        Image image = os.imagesV2().create(
                Builders.imageV2()
                        .name("Cirros 0.5.2 x64")
                        .containerFormat(ContainerFormat.BARE)
                        .visibility(Image.ImageVisibility.PUBLIC)
                        .diskFormat(DiskFormat.QCOW2)
                        .minDisk((long) 0)
                        .minRam((long) 0)
                        .build()
        );
        System.out.println(JSONObject.toJSONString(image));
        // Create a Payload - we will use URL in this example
        Payload<File> filePayload = Payloads.create(new File("D:\\cirros-0.5.2-aarch64-disk.img"));
// Get image object to use, or send null
        ActionResponse upload = os.imagesV2().upload(
                image.getId(),
                filePayload,
                image);
        return JSONObject.toJSONString(upload);
    }
}

